<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no" />
    <title>沟通中</title>
    <link rel="stylesheet" type="text/css" href="__STATIC__/newcj/css/themes.css?v=2017129">
    <link rel="stylesheet" type="text/css" href="__STATIC__/newcj/css/h5app.css">
    <link rel="stylesheet" type="text/css" href="__STATIC__/newcj/fonts/iconfont.css?v=2016070717">
    <script src="__STATIC__/qqFace/js/jquery.min.js"></script>
    <script src="__STATIC__/newcj/js/dist/flexible/flexible_css.debug.js"></script>
    <script src="__STATIC__/newcj/js/dist/flexible/flexible.debug.js"></script>
    <script src="__STATIC__/qqFace/js/jquery.qqFace.js"></script>
</head>
<style>

    .qqFace { margin-top: -180px; background: #fff; padding: 2px; border: 1px #dfe6f6 solid; width: 80%}
    .qqFace table { width: 100% }
    .qqFace table td { padding: 0px; }
    .qqFace table td img { cursor: pointer; border: 1px #fff solid; }
    .qqFace table td img:hover { border: 1px #0066cc solid; }
</style>
<body ontouchstart>
<div class='fui-page-group'>
<div class='fui-page chatDetail-page'>
    <div class="chat-header flex">
        <i class="icon icon-toleft t-48" onclick='redi("__DOMAIN__/index/index/lists?fromid={$fromid}")'></i>
        <span class="shop-titlte t-30"></span>
        <span class="shop-online t-26"></span>
        <span class="into-shop">进店</span>
    </div>
    <div class="fui-content navbar" style="padding:1.2rem 0 1.35rem 0;">
        <div class="chat-content">
            <p style="display: none;text-align: center;padding-top: 0.5rem" id="more"><a>加载更多</a></p>
<!--            <p class="chat-time"><span class="time">2222</span></p>-->

<!--            <div class="chat-text section-left flex">-->
<!--            <span class="char-img" style="background-image: url(__DOMAIN__/static/newcj/img/123.jpg)"></span>-->
<!--            <span class="text"><i class="icon icon-sanjiao4 t-32"></i>你好</span>-->
<!--            </div>-->

<!--            <div class="chat-text section-right flex">-->
<!--            <span class="text"><i class="icon icon-sanjiao3 t-32"></i>你好</span>-->
<!--            <span class="char-img" style="background-image: url(__DOMAIN__/static/newcj/img/132.jpg)"></span>-->
<!--            </div>-->

        </div>
    </div>
    <div class="fix-send flex footer-bar">
        <i class="icon icon-emoji1 t-50"></i>
        <input class="send-input t-28" maxlength="200" id="saytext">
        <input type="file" name="pic" id="file" style="display: none">
        <i class="icon icon-add image_up t-50" style="color: #888;"></i>
        <span class="send-btn">发送</span>
    </div>
</div>
</div>

</body>
<script>
    var fromid = {$fromid};

    var toid = {$toid};

    var from_head = "{$from_head}";

    var  to_head = "{$to_head}";

    var to_name="{$to_name}";

    var API_URL = "__DOMAIN__/index.php/api/chat/";
    window.WebSocket = window.WebSocket || window.MozWebSocket;
    if (!window.WebSocket){
        alert("WebSocket not supported by this browser");

    }
    var setIntervalId = null;
    var ws = new WebSocket("__WEBSOCKET__");
    ws.onopen = function(){
        //当WebSocket创建成功时，触发onopen事件
        console.log("open");
        setIntervalId = setInterval(heart, 5000)
        //ws.send("hello1"); //将消息发送到服务端
    }
    ws.onmessage = function(e){
        //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
        if(e && e.data && e.data != '') {
            var json = eval("(" + e.data + ")");
            switch (json.type) {
                case 'init':
                    var bind = '{"type":"bind","fromid":"' + fromid + '"}';
                    ws.send(bind);
                    // get_head(fromid, toid);
                    // get_name(toid);
                    ws.send('{"type":"online", "toid":"'+ toid +'", "fromid":"'+ fromid +'"}'); //判断聊天对象是否在线
                    message_load();
                    changeNoRead(); //消息已读
                    return;
                case 'chat':
                    // 发送人是我们的聊天对象 且 接收人是自己
                    if (toid == json.fromid && fromid == json.toid) {
                        $(".shop-titlte").text("与"+to_name+"聊天中...");
                        $(".chat-content").append('<p class="chat-time"><span class="time">'+mydate(json.time) +'</span></p><div class="chat-text section-left flex"><span class="char-img" style="background-image: url(/' + to_head + ')"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i>' + replace_em(json.data) + '</span> </div>');
                        $(".chat-content").scrollTop(3000); // 滚动条
                        $(".time").text(mydate(json.time));
                        changeNoRead(); //消息已读
                    }

                    return;
                case "save":
                    if(json.toid == toid) {
                        // 避免多设备登录，save_message会请求多次
                        save_message(json);
                    }
                    if(json.isread==1){
                        $(".shop-online").text("在线");
                    }else{
                        $(".shop-online").text("不在线");
                        $(".shop-titlte").text("");
                    }
                    return;
                case  "online":
                    if(json.status==1){
                        $(".shop-online").text("在线");
                    }else{
                        $(".shop-online").text("不在线");
                        $(".shop-titlte").text("");
                    }
                    return;
                case "say_img":

                    $(".chat-content").append('<p class="chat-time"><span class="time">'+mydate(json.time) +'</span></p><div class="chat-text section-left flex"><span class="char-img" style="background-image: url(/'+to_head+')"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i><img width="120em" height="120em" src="/uploads/'+json.data+'"></span> </div>');

                    $(".chat-content").scrollTop(3000);

                    return;
            }
        }
    }
    ws.onclose = function(e){
        //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
        console.log("close");
        window.clearInterval(setIntervalId); // 清除定时器
    }


    $('.send-btn').click(function(){
        var text = $('.send-input').val();
        if(!text || text == ''){
            alert('消息不能为空');
            return ;
        }
        var message = '{"data":"'+text+'","type":"chat","fromid":"'+fromid+'","toid":"'+toid+'"}';
        // var message = '{"data":"'+text+'","type":"chat"}';

        $(".chat-content").append('<div class="chat-text section-right flex"><span class="text"><i class="icon icon-sanjiao3 t-32"></i>'+replace_em(text)+'</span> <span class="char-img" style="background-image: url(/'+from_head+')"></span> </div>');
        $(".chat-content").scrollTop(3000); // 滚动条
        ws.send(message);

        $(".send-input").val("");
    });


    function save_message(message){
        $.post(
            API_URL+"save_message" ,
            message,
            function(){

            },'json'
        )
    }
    // 发送心跳检测
    function heart(){
        ws.send('{"type":"heart"}');
    }
    // 直接通过页面渲染
   /* function get_head(fromid,toid){
        $.post(
            API_URL+"get_head",
            {"fromid":fromid,"toid":toid},
            function(e){
                from_head = e.from_head;
                to_head = e.to_head;
            },'json'
        );
    }

    function  get_name(toid){
        $.post(
            API_URL+"get_name",
            {"uid":toid},
            function(e){
                to_name = e.toname;
                $(".shop-titlte").text("与"+to_name+"聊天中...");
                console.log(e);
            },'json'
        );
    }*/
    function message_load(){
        $.post(
            API_URL +"load",
            {"fromid":fromid,"toid":toid},
            function(e){
                $.each(e,function(index,content){
                    if(fromid==content.fromid){
                        if(content.type==2){
                            $(".chat-content").append('<p class="chat-time"><span class="time">'+mydate(content.time) +'</span></p><div class="chat-text section-right flex"><span class="text"><i class="icon icon-sanjiao3 t-32"></i><img width="120em" height="120em" src="/uploads/'+content.content+'"></span> <span class="char-img" style="background-image: url(/'+from_head+')"></span> </div>');

                        }else{
                            $(".chat-content").append('<p class="chat-time"><span class="time">'+mydate(content.time) +'</span></p><div class="chat-text section-right flex"><span class="text"><i class="icon icon-sanjiao3 t-32"></i>'+replace_em(content.content)+'</span> <span class="char-img" style="background-image: url(/'+from_head+')"></span> </div>');
                        }
                    }else{
                        if(content.type==2){

                            $(".chat-content").append('<p class="chat-time"><span class="time">'+mydate(content.time) +'</span></p><div class="chat-text section-left flex"><span class="char-img" style="background-image: url(/'+to_head+')"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i><img width="120em" height="120em" src="/uploads/'+content.content+'"></span> </div>');
                        }else{
                            $(".chat-content").append('<p class="chat-time"><span class="time">'+mydate(content.time) +'</span></p><div class="chat-text section-left flex"><span class="char-img" style="background-image: url(/'+to_head+')"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i>'+replace_em(content.content)+'</span> </div>');
                        }
                    }
                })
                $(".chat-content").scrollTop(3000); // 滚动条
            },'json'
        );
    }

    $(function(){

        $('.icon-emoji1').qqFace({

            assign:'saytext',

            path:'__STATIC__/qqFace/arclist/'	//表情存放的路径

        });

        $(".sub_btn").click(function(){

            var str = $("#saytext").val();

             // $("#show").html(replace_em(str));

        });

    });

    //查看结果

    function replace_em(str){

        str = str.replace(/\</g,'&lt;');

        str = str.replace(/\>/g,'&gt;');

        str = str.replace(/\n/g,'<br/>');

        str = str.replace(/\[em_([0-9]*)\]/g,'<img src="__STATIC__/qqFace/arclist/$1.gif" border="0" />');
        return str;

    }


    $(".image_up").click(function(){
        $("#file").click();
    })

    $("#file").change(function(){

        formdata = new FormData();
        formdata.append('fromid',fromid);
        formdata.append('toid',toid);
        // formdata.append('online',online);
        formdata.append('file',$("#file")[0].files[0]);

        $.ajax({
            url:API_URL+"uploadimg",
            type:'POST',
            cache:false,
            data:formdata,
            dataType:'json',
            processData:false,
            contentType:false,
            success:function(data,status,xhr){
                if(data.code==0){
                    $(".chat-content").append('<div class="chat-text section-right flex"><span class="text"><i class="icon icon-sanjiao3 t-32"></i><img width="120em" height="120em" src="/uploads/'+data.data.content+'"></span> <span class="char-img" style="background-image: url(/'+from_head+')"></span> </div>');

                    $(".chat-content").scrollTop(3000);

                    var message = '{"data":"'+data.data.content+'","fromid":"'+fromid+'","toid":"'+toid+'","type":"say_img"}';
                    $("#file").val("");
                    ws.send(message);
                }else{
                    alert(data.msg);
                }



            }
        });
    })

    /**
     *根据时间戳格式化为日期形式
     */
    function mydate(nS){
        return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
    }
    /**将未读的消息全部修改为已读**/
    function changeNoRead(){
        $.post(
            API_URL+"changeNoRead",
            {"fromid":fromid,"toid":toid},
            function(){

            },'json'
        )
    }

    function redi(url){
        window.location.href=url;
    }
</script>
</html>
